import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  SET_TOKEN: (state, newToken) => {
    state.token = newToken
    setToken(newToken)
  },
  removeToken(state) {
    removeToken()
    state.token = ''
  },
  updateUserInfo(state, info) {
    state.userInfo = info
  }
}

const actions = {
  // user login
  async  login(context, data) {
    const { token } = await login(data)
    context.commit('SET_TOKEN', token)
  },

  // get user info
  async getUserInfo(context) {
    const res = await getInfo()
    context.commit('updateUserInfo', res.userInfo)
    return res.menuList
  },
  // user logout
  logout(context) {
    context.commit('removeToken')
    context.commit('updateUserInfo', {})
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

